package com.caigou.modules.info.ui.publish

import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.widget.ImageView
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.GlideEngine
import com.caigou.modules.info.R
import com.caigou.modules.info.databinding.ActivityInfoPublishBinding
import com.caigou.modules.info.viewmodel.InfoPublishViewModel
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.lwkandroid.widget.ngv.DefaultNgvAdapter
import com.lwkandroid.widget.ngv.NgvChildImageView
import dagger.hilt.android.AndroidEntryPoint
import java.io.File

/**
 * @author #Suyghur.
 * Created on 2021/12/01
 */
@Route(path = RouterPath.Info.PAGE_INFO_PUBLISH)
@AndroidEntryPoint
class InfoPublishActivity : BaseActivity() {

    private lateinit var binding: ActivityInfoPublishBinding

    private val infoPublishViewModel: InfoPublishViewModel by viewModels()

    private val coverUrls = mutableListOf<String>()

    private val picUrls = mutableListOf<String>()

    private var type = 0

    private val coverAdapter: DefaultNgvAdapter<String> by lazy {
        DefaultNgvAdapter(1, GlideDisplay())
    }

    private val picAdapter: DefaultNgvAdapter<String> by lazy {
        DefaultNgvAdapter(100, GlideDisplay())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityInfoPublishBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.infoPublishLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        binding.infoPublishNgvCover.setSingleImageSize(TypedValue.COMPLEX_UNIT_DIP, 150, 150)
        coverAdapter.setOnChildClickListener(object : DefaultNgvAdapter.OnChildClickedListener<String> {
            override fun onPlusImageClicked(plusImageView: ImageView?, dValueToLimited: Int) {
                openCoverGallery()
            }

            override fun onContentImageClicked(position: Int, data: String?, childImageView: NgvChildImageView?) {
                data?.apply {
                    showImgsPreview(this@InfoPublishActivity, coverUrls, coverUrls.indexOf(this))
                }
            }

            override fun onImageDeleted(position: Int, data: String?) {
                data?.apply {
//                    urls.remove(this)
                }
            }
        })
        binding.infoPublishNgvCover.adapter = coverAdapter

        binding.infoPublishNgvPic.setSingleImageSize(TypedValue.COMPLEX_UNIT_DIP, 150, 150)
        picAdapter.setOnChildClickListener(object : DefaultNgvAdapter.OnChildClickedListener<String> {
            override fun onPlusImageClicked(plusImageView: ImageView?, dValueToLimited: Int) {
                openGallery()
            }

            override fun onContentImageClicked(position: Int, data: String?, childImageView: NgvChildImageView?) {
                data?.apply {
                    showImgsPreview(this@InfoPublishActivity, picUrls, picUrls.indexOf(this))
                }
            }

            override fun onImageDeleted(position: Int, data: String?) {
                data?.apply {
//                    urls.remove(this)
                }
            }
        })
        binding.infoPublishNgvPic.adapter = picAdapter

        binding.infoPublishRgSelector.setOnCheckedChangeListener { group, _ ->
            type = when (group.checkedRadioButtonId) {
                binding.infoPublishBtnHk.id -> 1
                binding.infoPublishBtnMacao.id -> 2
                binding.infoPublishBtnSingapore.id -> 3
                binding.infoPublishBtnTw.id -> 4
                else -> 0
            }
        }
        binding.infoPublishBtnSubmit.setOnClickListener {
            val title = binding.infoPublishEtTitle.text.toString()
            val content = binding.infoPublishEtContent.text.toString()
            if (TextUtils.isEmpty(title)) {
                showToast("标题不能为空！")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(content)) {
                showToast("内容不能为空！")
                return@setOnClickListener
            }
            if (type <= 0) {
                showToast("请选择彩种！")
                return@setOnClickListener
            }
            if (coverUrls.isNullOrEmpty()) {
                showToast("请选择封面")
                return@setOnClickListener
            }
            val cover = File(coverUrls[0])
            val files = mutableListOf<File>()
            picUrls.forEach {
                files.add(File(it))
            }

            infoPublishViewModel.publishInfo(cover, files, title, content, AppBackgroundInfo.instance.userBean!!.userId, type)
        }

        binding.infoPublishTvBack.setOnClickListener {
            finish()
        }
    }

    override fun observeViewModel() {
        observe(infoPublishViewModel.publishLiveData, ::handleInfoPublish)
    }

    private fun handleInfoPublish(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("资料发布失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
//                LiveDataBus.get().with(BusKey.ARTICLE_REPLY_SUCCESS, Any::class.java).value = Any()
                this.finish()
            }
        }
    }

    private fun openCoverGallery() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .theme(R.style.picture_WeChat_style)
            .imageEngine(GlideEngine.instance)
            .imageSpanCount(4)
            .isReturnEmpty(true)
            .selectionMode(PictureConfig.SINGLE)
            .maxSelectNum(1)
            .isPreviewImage(true)
            .isCamera(true)
            .isZoomAnim(true)
            .setCameraImageFormat(PictureMimeType.PNG)
            .isEnableCrop(false)
            .isCompress(true)
            .compressQuality(80)
            .synOrAsy(false)
            .withAspectRatio(1, 1)
            .minimumCompressSize(100)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    result?.apply {
                        coverUrls.clear()
                        coverUrls.add(this[0].compressPath)
                        coverAdapter.dataList = coverUrls
                    }
                }

                override fun onCancel() {
                }

            })
    }

    private fun openGallery() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .theme(R.style.picture_WeChat_style)
            .imageEngine(GlideEngine.instance)
            .imageSpanCount(4)
            .isReturnEmpty(true)
            .selectionMode(PictureConfig.MULTIPLE)
            .maxSelectNum(9)
            .isPreviewImage(true)
            .isCamera(true)
            .isZoomAnim(true)
            .setCameraImageFormat(PictureMimeType.PNG)
            .isEnableCrop(false)
            .isCompress(true)
            .compressQuality(80)
            .synOrAsy(false)
            .withAspectRatio(1, 1)
            .minimumCompressSize(100)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    result?.apply {
                        picUrls.clear()
                        forEach {
                            picUrls.add(it.compressPath)
                        }
                        picAdapter.dataList = picUrls
                    }
                }

                override fun onCancel() {
                }

            })
    }
}